
package com.geezdata.cps.sdk3rd.wechat.method;

import java.io.IOException;
import java.util.SortedMap;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.geezdata.cps.base.utils.HttpClientUtil;
import com.geezdata.cps.base.utils.JaxbUtil;
import com.geezdata.cps.sdk3rd.wechat.enums.RedpackSceneEnum;
import com.geezdata.cps.sdk3rd.wechat.request.WechatHongbaoRequest;
import com.geezdata.cps.sdk3rd.wechat.response.WechatHongbaoResult;

public class WechatHongbao extends WechatPay implements Wechat<WechatHongbaoRequest, WechatHongbaoResult> {
	private static final Logger logger = LoggerFactory.getLogger(WechatHongbao.class);
	
	public static String HONGBAO_URL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
	
	@Override
	public WechatHongbaoResult execute(WechatHongbaoRequest request) {
		SortedMap<String, Object> params = prepareParams(request);
		generateSign(params, request.getPayKey());
		String requestXML = convert2Xml(params);
		
		try {
			String rspStr = HttpClientUtil.post(HONGBAO_URL, requestXML, HttpClientUtil.sslHttpClient(
					request.getKeyStorePath(), request.getKeyStorePassword(), request.getKeyStoreType()));
			if(rspStr.contains("xml")){
				String xmlRspStr = rspStr.replaceAll("\r|\n", "");
				WechatHongbaoResult result= (WechatHongbaoResult)JaxbUtil.converyToJavaBean(
						xmlRspStr, WechatHongbaoResult.class);
				return result;
			 }
		} catch (IOException e) {
			logger.error("WeixinHongbao::execute failed url {}, params {}", HONGBAO_URL, requestXML);
		}
		
		return null;
	}
	
	private SortedMap<String, Object> prepareParams(WechatHongbaoRequest request) {
		SortedMap<String, Object> params = new TreeMap<String, Object>();
        params.put("nonce_str",generateNonceStr());
        params.put("mch_billno", request.getBillNo());
        params.put("mch_id", request.getMchId());  
        params.put("wxappid", request.getAppId()); 
        params.put("send_name", request.getSendName());  
        params.put("re_openid", request.getOpenId()); 
        params.put("total_amount", request.getTotalAmount());   
        params.put("total_num", request.getTotalNum());  
        params.put("wishing", request.getWishing());  
        params.put("client_ip", request.getClientIp());  
        params.put("act_name", request.getActName());  
        params.put("remark", request.getRemark());  
        params.put("scene_id", RedpackSceneEnum.抽奖.getName());
        return params;  
	}
}
